const express = require('express');
const fs = require('fs');
let ejs = require('ejs');
let app = express()
const sings = require('./data.js');
const path = require('path')
app.get('/',(req,res)=>{
    let data = fs.readFileSync('./index.html');
    res.send(data)
})


let cacheIP=[]

// 中间件，记录每个请求的url地址和ip
app.use((req,res,next)=>{
    let {ip, url} = req;
    fs.appendFileSync(path.resolve(__dirname,'./source/access.log'), `${ip} ${url}\r\n`)
    next()
})

app.use(express.static(path.resolve(__dirname,'./source')))

let routers = express.Router()
function routerMiddle (req,res,next){ // 中间件，查看路由请求中是否有code参数
    if(req.query.code){
        next()
    }else{
        res.send('url错误')
    }
}
routers.get('/:id.html',(req,res)=>{
    let str = fs.readFileSync('./index.html');
    let id = req.params.id;
    let options = sings[id]
    if(!options){
        // res.send('404 未找到相对应页面')
        res.redirect('http://www.baidu.com')
    }
    
    let template = ejs.render(str.toString(), options);
    res.statusCode = 200;
    res.statusMessage=" i love you "
    res.setHeader('dd','bb')
    res.send(template)
    // res.send(__dirname+'/index.html')
})

routers.get('/add',routerMiddle,(req,res)=>{
    res.send('/add')
})
routers.get('/car',routerMiddle,(req,res)=>{
    res.send('/car')
})

app.use('/',routers)


app.listen(3000,()=>{
    console.log('server connect success...')
})